local japi = require 'jass.japi'
local jass = require 'jass.common'

local md5 = japi.md5 

local text = {}
setmetatable(text,text)

--- 存放所有text
text.alltexts = {}

--- 生成的FDF
text.fonts = {}

--- FLAG 列表
text.flags = {
    ['固定大小'] = "FIXEDSIZE",                 -- 有这个flag 文本边距 不会影响文本的大小
    ['密码样式'] = "PASSWORDFIELD",	            -- 所有字符全部变成 * 
    ['颜色纯灰'] = "FIXEDCOLOR",                -- 颜色纯灰
    ['等宽文字'] = "NONPROPORTIONAL",           -- 所有文本宽度相等
    ['禁用自适应'] = "NOWRAP",                  -- 文本自适应关闭
    ['禁用颜色代码'] = "IGNORECOLORCODES",	    -- 颜色代码变成纯文本
    ['禁用换行符'] = "IGNORENEWLINES",          -- 换行符效果屏蔽
    -- ['悬停高亮'] = "HIGHLIGHTONMOUSEOVER",	    -- 没卵用
}

--- 模板
text.template = [[
Frame "TEXT" "%s" {
LayerStyle "IGNORETRACKEVENTS",
FrameFont "%s", %.04f, "%s",
FontJustificationH JUSTIFY%s,
FontJustificationV JUSTIFY%s,
%sFontShadowColor %.02f %.02f %.02f %.02f,
%sFontShadowOffset %.04f %.04f,
%sFontFlags "%s",
%sFontHeight %.04f,
}
]]

--- 转换flags
function text.convert_flags(value)
    local result = "FIXEDSIZE"
    if type( value ) ~= 'string' then
        return result
    end
    local keyworlds = { }
    for name in value:gmatch( "[^|]+" ) do
        if text.flags[name] then
            keyworlds[#keyworlds+1] = text.flags[name]
        end
    end
    if #keyworlds > 0 then
        result = table.concat( keyworlds , "|" )
    end
    return result
end

--- 构造FDF
function text.load_fdf(self)
    local shadow = rawget(self, 'shadow_color')
    local flags = rawget(self, 'flags')
    local height = rawget(self, 'height')
    local names = { }
    names[#names+1] = self.font
    names[#names+1] = tonumber(self.font_size)
    names[#names+1] = self.outline and '1' or '2'
    names[#names+1] = self.justH:upper()
    names[#names+1] = self.justV:upper()
    if shadow then 
        names[#names+1] = ('%08X%.04f%.04f'):format(shadow, self.shadow_offset_x, self.shadow_offset_y)
    end 
    if flags then 
        names[#names+1] = flags
    end 
    if height then 
        names[#names+1] = tonumber(height)
    end 
    local name = md5(table.concat(names))
    if not text.fonts[name] then 

        -- 加载FDF了
        local params = {
            name,
            self.font,
            self.font_size / 1000,
            self.outline and "OUTLINE" or '',
            self.justH,
            self.justV,
        }

        if shadow then 
            params[#params+1] = ""
            params[#params+1] = ((shadow << 40) >> 56) / 255
            params[#params+1] = ((shadow << 48) >> 56) / 255
            params[#params+1] = ((shadow << 56) >> 56) / 255
            params[#params+1] = ((shadow << 32) >> 56) / 255
            params[#params+1] = ""
            params[#params+1] = self.shadow_offset_x / 1920 * 0.8
            params[#params+1] = self.shadow_offset_y / 1080 * 0.6
        else 
            params[#params+1] = "//"
            params[#params+1] = 0
            params[#params+1] = 0
            params[#params+1] = 0
            params[#params+1] = 0
            params[#params+1] = "//"
            params[#params+1] = 0
            params[#params+1] = 0
        end 

        if flags then 
            params[#params+1] = ""
            params[#params+1] = text.convert_flags(flags)
        else
            params[#params+1] = "//"
            params[#params+1] = ""
        end 

        if height then 
            params[#params+1] = ""
            params[#params+1] = height / 1000
        else 
            params[#params+1] = "//"
            params[#params+1] = 0
        end 

        load_fdf( text.template:format( table.unpack(params)))
        text.fonts[name] = true
    end 
    return name
end 

local mt = extends(ac.frame){}

--类型
mt.type = 'text' 

--魔兽控件类型
mt._type = 'TEXT'

--识别名称
mt._name = '文本'

--文本内容
mt.text = ''

--文本字体
mt.font = 'fonts.ttf'
--mt.font = 'Fonts\\dfst-m3u.ttf'

--文本字体大小（font如果是'MasterFont'则该项无效）
mt.font_size = 12

--文本颜色
mt.color = 0xffffffff

--阴影描边
mt.outline = false

--文本阴影颜色
mt.shadow_color = 0xffffffff

--文本阴影偏移x
mt.shadow_offset_x = 0

--文本阴影偏移y
mt.shadow_offset_y = 0

--文本字体间距
mt.spacing = 0

--横向对齐方式 LEFT|RIGHT|CENTER
mt.justH = "LEFT"

--纵向对齐方式 TOP|BOTTOM|MIDDLE
mt.justV = "TOP"

-- 文本高度 1个当前文字大小的单位 即 文字为 12 则 该值基准为 12 
-- 该值影响控件的文本的上下实际高度 会连同文字大小一起改变 
-- 如果文本的 flags 包含固定大小则 则不会改变文字大小
mt.height = 0

--文本flag
---固定大小          有这个flag 文本边距 不会影响文本的大小
---密码样式          所有字符全部变成 * 
---颜色纯灰          颜色纯灰
---等宽文字          所有文本宽度相等
---禁自适应          文本自适应关闭
---禁颜色串          颜色代码变成纯文本
---禁换行符          换行符效果屏蔽
mt.flags = nil

--- 创建控件
function mt.new(parent, text, x, y, w, h,font_size,align,outline)
    local data = {
        parent = parent,
        text = text,
        font_size = font_size,
        w = w,
        h = h,
        x = x,
        y = y,
        align = align,
    }
    if outline then
        --data.outline = true
        data.shadow_offset_x = outline
        data.shadow_offset_y = -outline
        data.shadow_color = 0xff000000
    end
    local control = class.text:builder(data)
    return control
end 

--- 输出
function mt:__tostring()
    return string.format('[文本]->%d',self.handle or 0)
end


--- 转换
function mt.convert(handle, parent, is_default)
    local control = text.alltexts[handle]
    if control then 
        return control
    end 
    control = ac.frame.convert(handle, 'text', parent, is_default)
    text.alltexts[handle] = control
    return control
end


--- 初始化
local x_p = {'LEFT','CENTER','RIGHT'}
local y_p = {'BOTTOM','MIDDLE','TOP'}
function mt:init()
    if self.handle then return end
    if self.align then
        local x = (self.align-1)%3 + 1
        local y = (math.ceil(self.align/3)-1)%3 + 1
        self.justH = x_p[x]
        self.justV = y_p[y]
    end

    self.justH = self.justH:upper()
    self.justV = self.justV:upper()
    local handle = japi.CreateFrameByTagName( self._type, self._name, self.parent.handle, text.load_fdf(self), self._index )
    if not handle or handle == 0 then
        ac.frame.remove(self)
        log.error('创建text失败')
        return
    end
    self.handle = handle

    text.alltexts[handle] = self
    ac.frame.allframes[handle] = self
    -- w 设为 0 代表自适应宽度
    if rawget(self,"w") ~= 0 then 
        self:set_width(self.w)
    end
    -- h 设为 0 代表自适应高度
    if rawget(self,"h") ~= 0 then 
        self:set_height(self.h)
    end
    self:set_position(self.x,self.y)
    -- self:set_font(self.font,self.font_size)
    self:set_color(self.color)
    self:set_spacing(self.spacing)
    self:set_text(self.text)
    if self.show_flag then
        self.show_flag = false
        self:show()
    else 
        self.show_flag = true
        self:hide()
    end
    return self
end 

---删除控件
function mt:remove()
    if self.removed then return end
    if self:is_simple() then return end
    text.alltexts[self.handle] = nil
    ac.frame.remove(self)
end

--- 设置文本字体和大小
function mt:set_font(font_path,font_size,outline)
    if self.removed then return end
    self.font = font_path
    self.font_size = font_size
    japi.FrameSetTextFont(self.handle,self.font,self.font_size / 1000, outline and 1 or 0)
end

--- 设置间距 
function mt:set_spacing(spacing)
    self.spacing = spacing
    japi.FrameSetTextFontSpacing(self.handle,spacing)
end

--- 设置文本
function mt:set_text(text)
    if self.removed then return end
    japi.FrameSetText(self.handle,text or '')
end

--- 获取文本
function mt:get_text()
    if self.removed then 
        return self.text
    end
    return japi.FrameGetText(self.handle)
end

--- 获取宽度
function mt:get_width()
    if self.removed then 
        return self.w
    end
    return japi.FrameGetTextWidth(self.handle) / 0.8 * 1920
end 

--- 获取高度
function mt:get_height()
    if self.removed then 
        return self.h
    end
    return japi.FrameGetTextHeight(self.handle) / 0.6 * 1080
end 

--- 设置颜色
function mt:set_color(color)
    if self.removed then return end
    self.color = color
    japi.FrameSetTextColor(self.handle,color)
end


--- 获取颜色
function mt:get_color()
    return self.color 
end

local japi2 = require 'util.japi2'

-- 设置缩放
function mt:set_size(size)
    if self.removed then return end
    japi2.FrameSetFontHeight(self.handle, size * self.font_size / 1000)
end

-- 设置缩放
function mt:set_scale(size)
    if self.removed then return end
    japi.FrameSetScale(self.handle, size)
end

-- ac.hardware:on '窗口大小刷新' (function()
--     for handle,control in pairs(text.alltexts) do 
--         if rawget(control,"w") ~= 0 then 
--             japi.FrameSetWidth(control.handle, control.w / 1920 * 0.8)
--         end
--         if rawget(control,"h") ~= 0 then 
--             japi.FrameSetHeight(control.handle, control.h / 1080 * 0.6)
--         end 
--     end 
-- end)

class.text = mt



return mt